package com.controller.api;

import com.alibaba.fastjson.JSON;
import com.biz.*;
import com.controller.backend.BaseController;
import com.core.Result;
import com.core.ResultGenerator;
import com.entity.model.*;
import com.util.Base64;
import com.util.HttpRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Condition;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.util.CalendarUtil.getAddDays2;

/**
 * Created by jc on 2019/11/16.
 */
@RestController("apiCustomerController")
@RequestMapping("/api/customerInfo")
public class CustomerController extends BaseController<Customer> {
    @Autowired
    private CustomerBiz customerBiz;

    @Autowired
    private BillBiz billBiz;

    @Autowired
    private SmsCodeAuthBiz smsCodeAuthBiz;

    @Autowired
    private BdTeamCodeLogBiz bdTeamCodeLogBiz;

    @Autowired
    private CustomerNotesBiz customerNotesBiz;

    @Autowired
    private ExperienceAccountBiz experienceAccountBiz;

    //用户详情
    @RequestMapping(value = "/detail")
    public Result detail(@RequestParam Integer customerId) {
        if (customerId == null) {
            return ResultGenerator.genFailResult("用户编号不能为空");
        }
        Customer customer = customerBiz.findById(customerId);
        if (customer.getVipEndDate() != null) {
            long diff = customer.getVipEndDate().getTime() - new Date().getTime();
            long day = diff / (1000 * 24 * 60 * 60);
            customer.setDays((int) day);
        }
        return ResultGenerator.genSuccessResult(customer);
    }

    //用户修改头像
    @RequestMapping(value = "/updateCustomerImg")
    public Result updateCustomer(@RequestParam Integer customerId, @RequestParam String headImgUrl) {
        if (customerId == null) {
            return ResultGenerator.genFailResult("用户编号不能为空");
        }
        Customer customer = customerBiz.findById(customerId);
        customer.setHeadImgUrl(headImgUrl);
        customerBiz.update(customer);
        return ResultGenerator.genSuccessResult(customer);
    }

    //用户修改绑定手机号码
    @RequestMapping(value = "/updateCustomerAccount")
    public Result updateCustomerImg(@RequestParam Integer customerId, @RequestParam String phone, @RequestParam Integer smsId, @RequestParam String code) throws Exception {
        if (customerId == null) {
            return ResultGenerator.genFailResult("用户编号不能为空");
        }
        if (StringUtils.isBlank(code)) {
            return ResultGenerator.genFailResult("验证码不能为空");
        }
        if (smsId == null) {
            return ResultGenerator.genFailResult("短信编号不能为空");
        }

        Condition condition = new Condition(SmsCodeAuth.class);
        condition.createCriteria().andEqualTo("id", smsId).andEqualTo("smsCode", code).andEqualTo("phone", phone);
        if (smsCodeAuthBiz.findByCondition(condition).size() == 0) {
            return ResultGenerator.genFailResult("验证码错误");
        }
        SmsCodeAuth smsCodeAuth = smsCodeAuthBiz.findByCondition(condition).get(0);
        if (smsCodeAuth.getId() > 0) {
            condition.createCriteria().andLessThan("expiredTime", new Date());
            smsCodeAuth = smsCodeAuthBiz.findByCondition(condition).get(0);
            if (smsCodeAuth.getId() > 0) {
                smsCodeAuthBiz.deleteById(smsCodeAuth.getId());
                Customer customer = customerBiz.findBy("account", phone);
                if (customer != null) {
                    return ResultGenerator.genFailResult("该号码已被绑定");
                }
                customer = customerBiz.findById(customerId);
                customer.setAccount(phone);
                customer.setPassword("123456");
                customerBiz.update(customer);

                if (customer.getParentBdId() == 13) {
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Map<String, Object> params = new HashMap<>();
                    params.put("user_id", customer.getId());
                    params.put("user_mobile", customer.getAccount());
                    params.put("user_name", customer.getNickName().replace("\'", "").replace("\"", ""));

                    String hourStr = "";
                    String minuteStr = "";
                    String secondStr = "";
                    Calendar now = Calendar.getInstance();
                    Integer hour = now.get(Calendar.HOUR_OF_DAY);
                    if (hour < 10) {
                        hourStr = "0" + hour.toString();
                    } else {
                        hourStr = hour.toString();
                    }
                    Integer minute = now.get(Calendar.MINUTE);
                    if (minute < 10) {
                        minuteStr = "0" + minute.toString();
                    } else {
                        minuteStr = minute.toString();
                    }
                    Integer second = now.get(Calendar.SECOND);
                    if (second < 10) {
                        secondStr = "0" + second.toString();
                    } else {
                        secondStr = second.toString();
                    }
                    String text = "" + hourStr + "9baAmjwJ" + minuteStr + "8LhjWTy9" + secondStr + "";
                    /*byte[] textByte = text.getBytes("UTF-8");*/
                    String sign = Base64.encode(text.getBytes("UTF-8"));
                    HttpRequest.sendPost("https://wxapp.yiluyouai.cn/integration/userUpdate", JSON.toJSONString(params), sign);
                }

                return ResultGenerator.genSuccessResult(customer);
            } else {
                return ResultGenerator.genFailResult("验证码已过期,请重新发送");
            }
        } else {
            return ResultGenerator.genFailResult("内部错误");
        }
    }

    //用户修改昵称
    @RequestMapping(value = "/updateCustomerNickName")
    public Result updateCustomerNickName(@RequestParam Integer customerId, @RequestParam String userName) throws Exception {
        if (customerId == null) {
            return ResultGenerator.genFailResult("用户编号不能为空");
        }
        Customer customer = customerBiz.findById(customerId);
        customer.setUserName(userName);
        customerBiz.update(customer);

        if (customer.getParentBdId() == 13) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Map<String, Object> params = new HashMap<>();
            params.put("user_id", customer.getId());
            params.put("user_mobile", customer.getAccount());
            params.put("user_name", customer.getNickName().replace("\'", "").replace("\"", ""));

            String hourStr = "";
            String minuteStr = "";
            String secondStr = "";
            Calendar now = Calendar.getInstance();
            Integer hour = now.get(Calendar.HOUR_OF_DAY);
            if (hour < 10) {
                hourStr = "0" + hour.toString();
            } else {
                hourStr = hour.toString();
            }
            Integer minute = now.get(Calendar.MINUTE);
            if (minute < 10) {
                minuteStr = "0" + minute.toString();
            } else {
                minuteStr = minute.toString();
            }
            Integer second = now.get(Calendar.SECOND);
            if (second < 10) {
                secondStr = "0" + second.toString();
            } else {
                secondStr = second.toString();
            }
            String text = "" + hourStr + "9baAmjwJ" + minuteStr + "8LhjWTy9" + secondStr + "";
            /*byte[] textByte = text.getBytes("UTF-8");*/
            String sign = Base64.encode(text.getBytes("UTF-8"));
            HttpRequest.sendPost("https://wxapp.yiluyouai.cn/integration/userUpdate", JSON.toJSONString(params), sign);
        }
        return ResultGenerator.genSuccessResult(customer);
    }

    //兑换券使用
    @RequestMapping(value = "/redemptionCode")
    public Result redemptionCode(@RequestParam Integer customerId, @RequestParam String code) {
        /*Condition cond = new Condition(BdTeamCodeLog.class);
        cond.createCriteria().andEqualTo("code", code);*/
        if (customerId == null) {
            return ResultGenerator.genFailResult("用户编号不能为空");
        }
        if (code == null) {
            return ResultGenerator.genFailResult("兑换券不能为空");
        }
        BdTeamCodeLog bdTeamCodeLog = bdTeamCodeLogBiz.getByCode(code);

        if (bdTeamCodeLog != null) {
            if (bdTeamCodeLog.getStatus() == 1) {
                return ResultGenerator.genFailResult("兑换码已被使用");
            }

            Customer customer = customerBiz.findById(customerId);
            if (customer == null) {
                return ResultGenerator.genFailResult("账户异常");
            }
            ExperienceAccount experienceAccount = experienceAccountBiz.findBy("experienceAccount", customer.getAccount());
            if (experienceAccount != null && bdTeamCodeLog.getVipLevel() == 1) {
                return ResultGenerator.genFailResult("该用户已使用过体验卡");
            }
            if (customer.getIsVip() == 1 && bdTeamCodeLog.getVipLevel() == 1) {
                return ResultGenerator.genFailResult("该用户已使用过体验卡");
            }
            if (customer.getIsVip() > 1 && bdTeamCodeLog.getVipLevel() == 1) {
                return ResultGenerator.genFailResult("会员用户无法使用体验卡");
            }

            customer.setIsVip(bdTeamCodeLog.getVipLevel());
            customer.setVipStartDate(new Date());
            if (bdTeamCodeLog.getVipLevel() == 1) {
                customer.setVipEndDate(getAddDays2(customer.getVipEndDate(), 90));

                experienceAccount = new ExperienceAccount();
                experienceAccount.setExperienceAccount(customer.getAccount());
                experienceAccountBiz.save(experienceAccount);
            }

            if (bdTeamCodeLog.getVipLevel() == 2) {
                if (customer.getIsVip() != null && customer.getVipEndDate() != null && customer.getIsVip() > 0) {
                    customer.setVipEndDate(getAddDays2(customer.getVipEndDate(), 365));
                } else {
                    customer.setVipEndDate(getAddDays2(new Date(), 365));
                }
            }

            if (bdTeamCodeLog.getVipLevel() == 3) {
                if (customer.getIsVip() != null && customer.getVipEndDate() != null && customer.getIsVip() > 0) {
                    customer.setVipEndDate(getAddDays2(customer.getVipEndDate(), 545));
                } else {
                    customer.setVipEndDate(getAddDays2(new Date(), 545));
                }
            }

            if (bdTeamCodeLog.getVipLevel() == 4) {
                if (customer.getIsVip() != null && customer.getVipEndDate() != null && customer.getIsVip() > 0) {
                    customer.setVipEndDate(getAddDays2(customer.getVipEndDate(), 90));
                } else {
                    customer.setVipEndDate(getAddDays2(new Date(), 90));
                }
            }
            customerBiz.update(customer);

            bdTeamCodeLog.setCustomerId(customerId);
            bdTeamCodeLog.setStatus(1);
            bdTeamCodeLogBiz.update(bdTeamCodeLog);

            return ResultGenerator.genSuccessResult(customer.getIsVip());
        } else {
            return ResultGenerator.genFailResult("兑换码不存在,请检查");
        }
    }


    //用户注销
    @RequestMapping(value = "/logCustomerOut")
    public Result logCustomerOut(@RequestParam Integer customerId) {
        if (customerId == null) {
            return ResultGenerator.genFailResult("用户号码不能为空");
        }
        Customer customer = customerBiz.findById(customerId);
        if (customer != null) {
            customerBiz.deleteById(customer.getId());

            customerNotesBiz.deleteByCustomerId(customerId);
            return ResultGenerator.genSuccessResult();
        }
        return ResultGenerator.genFailResult("账户注销产生异常");
    }


    //保存真实信息
    @RequestMapping(value = "/saveTrueInfo")
    public Result saveTrueInfo(@RequestParam Integer customerId, @RequestParam String trueName, @RequestParam String idCard) {
        if (customerId == null) {
            return ResultGenerator.genFailResult("用户号码不能为空");
        }
        Customer customerIdcard = customerBiz.findBy("idCard", idCard);
        if (customerIdcard != null) {
            return ResultGenerator.genFailResult("身份证已被绑定,请联系客服");
        }
        Customer customer = customerBiz.findById(customerId);
        if (customer != null) {
            String birthday = "";
            char[] number = idCard.toCharArray();
            boolean flag = true;
            if (number.length == 18) {
                for (int x = 0; x < number.length - 1; x++) {
                    flag = Character.isDigit(number[x]);
                }
            }
            if (flag && idCard.length() == 18) {
                String year = idCard.substring(6, 10);
                String month = idCard.substring(10, 12);
                String day = idCard.substring(12, 14);

                birthday = year + "-" + month + "-" + day;
            }

            customer.setTrueName(trueName);
            customer.setIdCard(idCard);
            customer.setBirthday(birthday);
            customerBiz.update(customer);
            return ResultGenerator.genSuccessResult();
        }
        return ResultGenerator.genFailResult("保存身份数据产生异常");
    }

    //获取提现实名信息
    @RequestMapping(value = "/getBankInfo")
    public Result saveBankInfo(@RequestParam Integer customerId) {
        if (customerId == null) {
            return ResultGenerator.genFailResult("用户号码不能为空");
        }
        Customer customer = customerBiz.findById(customerId);
        return ResultGenerator.genSuccessResult(customer);
    }

    //提现实名信息
    @RequestMapping(value = "/saveBankInfo")
    public Result saveBankInfo(@RequestParam Integer customerId, @RequestParam String bankName, @RequestParam String bankNo) {
        if (customerId == null) {
            return ResultGenerator.genFailResult("用户号码不能为空");
        }
        Customer customer = customerBiz.findById(customerId);
        if (customer != null) {
            customer.setBankName(bankName);
            customer.setBankNo(bankNo);
            customerBiz.update(customer);
            return ResultGenerator.genSuccessResult();
        }
        return ResultGenerator.genFailResult("保存身份数据产生异常");
    }


    @RequestMapping(value = "/promotionList")
    public Result promotionList(@RequestParam Integer customerId) {
        Condition condition = new Condition(Customer.class);
        condition.createCriteria().andEqualTo("parentCustomerId", customerId);
        List<Customer> customers = customerBiz.findByCondition(condition);
        return ResultGenerator.genSuccessResult(customers);
    }


    @RequestMapping(value = "/newCustomer")
    public Result newCustomer(Customer customer) {
        Customer customer1 = customerBiz.findBy("openid", customer.getOpenid());
        if (customer1 != null) {
            if (customer.getUserId() > 0) {
                customer1.setUserId(customer.getUserId());
            }
            customer1.setAccount(customer.getAccount());
            customerBiz.update(customer1);
        } else {
            customerBiz.save(customer);
        }
        System.out.print(customer.getUserId() + "|" + customer.getNickName() + "|" + customer.getOpenid());
        return ResultGenerator.genSuccessResult();
    }


    //生成图片
    @RequestMapping(value = "/savePhoto")
    public Result savePhoto(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "filename", required = false) MultipartFile filenames) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        //System.out.println(base64str);
        try {
            String path = request.getSession().getServletContext().getRealPath("/");
            path = path + "/" + "static" + "/" + "data" + "/" + "images" + "/";
            Date date = new Date();
            String hash = String.valueOf(date.getTime());//给照片自定义一个名字，用时间做名称，不会重复
            String fileName = hash + ".jpg";

            File dest = new File(path + fileName);

            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                filenames.transferTo(dest);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return ResultGenerator.genSuccessResult("/static/data/images/" + fileName);
        } catch (Exception e) {
            return ResultGenerator.genFailResult(e.getMessage());
            //e.printStackTrace();
        }
        //return ResultGenerator.genFailResult("上传失败");
    }
}
